use std::collections::HashMap;
use std::fs::File;
use std::io;
use std::io::BufRead;

pub fn converter(input: &str) -> String {
    let file_path = "chars.txt";
    let file = "pinyin.txt";
    let char_pinyin_hash = parse(file_path).expect("parse error");
    let map = read(file).unwrap();
    let mut pinyin_vec = Vec::new();
    let mut ans = Vec::new();
    for c in input.chars() {
        if let Some(pinyin) = char_pinyin_hash.get(&c.to_string()) {
            pinyin_vec.push(pinyin.clone());
        } else {
            pinyin_vec.push("".to_string());
        }
    }
    for i in pinyin_vec {
        if map.contains_key(&i) {
            let value = map.get(&i).unwrap();
            ans.push(value.clone());
        } else {
            ans.push(i.clone());
        }
    }
    // 将每个单词的首字符大写
    for i in ans.iter_mut() {
        *i = capitalize_word(i);
        break;
    }

    let result = ans.join(" ");
    // println!("{:?}",result);
    result
}

// 将单词的首字符大写
fn capitalize_word(word: &str) -> String {
    if word.is_empty() {
        return String::new();
    }
    let mut chars = word.chars();
    if let Some(first) = chars.next() {
        first.to_uppercase().collect::<String>() + chars.as_str()
    } else {
        word.to_string()
    }
}
fn parse(file_path: &str) -> io::Result<HashMap<String, String>> {
    let file = File::open(file_path)?;
    let reader = io::BufReader::new(file);
    let mut char_pinyin_hash = HashMap::new();
    for line in reader.lines() {
        let line = line?;
        let parts = line.split(':').collect::<Vec<&str>>();
        if parts.len() != 2 {
            continue; // 跳过格式不正确的行
        }
        let pinyin = parts[0].trim().to_string();
        let strs = parts[1].trim_matches('"').trim(); // 去掉前后的反转义字符和空格
        let chars: Vec<char> = strs.chars().collect();
        for c in chars {
            char_pinyin_hash.insert(c.to_string(), pinyin.clone());
        }
    }
    Ok(char_pinyin_hash)
}
fn read(file_path: &str) -> io::Result<HashMap<String, String>> {
    let file = File::open(file_path)?;
    let reader = io::BufReader::new(file);
    let mut map = HashMap::new();
    for line in reader.lines() {
        let line = line?;
        let parts: Vec<&str> = line.split_whitespace().collect();
        if parts.len() == 3 {
            map.insert(parts[0].to_string(), parts[2].to_string());
        }
    }

    Ok(map)
}
